package com.runtime.hongyunmanage.config;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化代码（可选）
        System.out.println("AuthFilter initialized");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 获取用户登录状态
        Object user = httpRequest.getSession().getAttribute("manage");

        // 获取请求路径
        String path = httpRequest.getRequestURI();

        // 检查是否需要跳转到登录页面
        if (user == null
                && !path.contains("/login")
                && !path.contains("/code")
                && !path.contains("/register") // 添加对注册页面的特殊处理
                && !path.contains("/manager/managercount") // 添加对 managercount 接口的特殊处理
                && !path.endsWith("css")
                && !path.endsWith("js")
                && !path.endsWith("jpg")
                && !path.endsWith("jpeg")
        ) {
            // 用户未登录，重定向到登录页面
            String contextPath = httpRequest.getContextPath();
            httpResponse.sendRedirect(contextPath + "/login.html");
        } else {
            // 用户已登录或请求验证码、注册页面、managercount 接口，继续执行后续的请求处理
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        // 销毁代码（可选）
        System.out.println("AuthFilter destroyed");
    }
}